package com.zzy.prototype.deepclone;

import com.zzy.prototype.Sheep;
import java.io.*;

public class DeepCloneSheep implements Cloneable, Serializable {
    public String name;
    public Sheep friendSheep;

    public DeepCloneSheep() {
        super();
    }

    //方式1：重写clone，对于所有的引用类型，实现其cloneable接口，单独对其进行处理
    @Override
    protected Object clone() {
        Object superClone = null;
        try {
            superClone = super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        DeepCloneSheep deepCloneSheep = (DeepCloneSheep) superClone;
        deepCloneSheep.friendSheep = (Sheep) friendSheep.clone();
        return deepCloneSheep;
    }


    //方式2：序列化
    public Object deepClone() {
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        ObjectInputStream ois = null;
        try {
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this);

            ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
            Object readObject = ois.readObject();
            return readObject;
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();

        } finally {
            try {
                ois.close();
                oos.close();
                bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return null;
    }

    @Override
    public String toString() {
        return "DeepCloneSheep{" +
                "name='" + name + '\'' +
                '}';
    }
}

class Client {
    public static void main(String[] args) {

        DeepCloneSheep sheep1 = new DeepCloneSheep();
        sheep1.name = "zzy";
        sheep1.friendSheep = new Sheep("mika", 28, "black");

        DeepCloneSheep sheep3 = (DeepCloneSheep) sheep1.clone();
        System.out.println("sheep1.friend>>>" + sheep1.friendSheep + ",sheep1.friend.hashCode>>>" + sheep1.friendSheep.hashCode());
        System.out.println("sheep3.friend>>>" + sheep3.friendSheep + ",sheep3.friend.hashCode>>>" + sheep3.friendSheep.hashCode());

        DeepCloneSheep sheep4 = (DeepCloneSheep) sheep1.deepClone();
        System.out.println("sheep4.friend>>>" + sheep4.friendSheep + ",sheep4.friend.hashCode>>>" + sheep4.friendSheep.hashCode());
    }
}